package cn.plushine.controller;

import cn.plushine.pojo.User;
import cn.plushine.service.IndexService;
import cn.plushine.utils.JWTUtils;
import cn.plushine.utils.ResMapUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 后台登录模块
 */
// Controller类描述
@Api(tags = "后台登录模块")
@RestController
@RequestMapping("/admin/acl/index")
public class IndexController {

    @Autowired
    IndexService indexService;

    // 用户登录
    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户信息", required = true, paramType = "body", dataType = "User")
    })
    @PostMapping("/login")
    public HashMap<String, Object> login(@RequestBody User user) {
        // 存储响应数据
        HashMap<String, Object> loginMap = new HashMap<>();
        try {
            // 调用service层判断是否登录成功（登录失败会在service层直接响应）
            User userDB = indexService.login(user.getUsername(), user.getPassword());

            // 封装payload
            HashMap<String, String> payLoad = new HashMap<>();
            payLoad.put("id", userDB.getId() + "");
            payLoad.put("username", userDB.getUsername());

            // 生成Token
            String token = JWTUtils.getToken(payLoad);

            // 封装成功数据
            loginMap = ResMapUtils.encapsulation(200, "登录成功", new HashMap() {
                {
                    put("token", token);
                }
            });
            // map.put("data", new HashMap<>().put("token", token)); // 这种方法不对，返回值为put的结果而非一个map
        } catch (Exception e) {
            // 封装失败数据
            loginMap = ResMapUtils.encapsulation(201, "登录失败", new HashMap<>());
        }
        // 响应结果
        return loginMap;
    }

    // 获取用户信息
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public HashMap<String, Object> info(HttpServletRequest request) {
        // 存储响应数据
        HashMap<String, Object> infoMap = new HashMap<>();

        // 从header中读取token
        String token = request.getHeader("token");

//         根据token读取payload中的用户id
        int userId = Integer.parseInt(JWTUtils.verifyToken(token).getClaims().get("id").asString());

        try {
            // 调用service层
            User infoDB = indexService.info(userId);
            // 返回用户信息
            infoMap = ResMapUtils.encapsulation(200, "用户信息获取成功", infoDB);
        } catch (Exception e) {
            infoMap = ResMapUtils.encapsulation(201, "用户信息获取失败", e.getMessage());
        }

        // 响应结果
        return infoMap;
    }

    // 用户退出登录
    @ApiOperation(value = "用户退出登录")
    @PostMapping("/logout")
    public HashMap<String, Object> logout() {
        // 响应结果
        return ResMapUtils.encapsulation(200, "退出登录成功", new HashMap<>());
    }

}
